import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

class FoodRecommendationsPage extends StatefulWidget {
  const FoodRecommendationsPage({Key? key}) : super(key: key);

  @override
  State<FoodRecommendationsPage> createState() =>
      _FoodRecommendationsPageState();
}

class _FoodRecommendationsPageState extends State<FoodRecommendationsPage> {
  final Dio dio = Dio();
  final String baseUrl = 'http://127.0.0.1:5000';

  List<Map<String, dynamic>> foods = [];
  List<String> categories = ['全部'];
  String selectedCategory = '全部';
  bool isLoading = true;
  String? error;

  @override
  void initState() {
    super.initState();
    _loadFoodData();
  }

  Future<String?> _getToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('auth_token');
      return token != null ? 'Bearer $token' : null;
    } catch (e) {
      print('获取token失败: $e');
      return null;
    }
  }

  Future<void> _loadFoodData() async {
    try {
      setState(() {
        isLoading = true;
        error = null;
      });

      final token = await _getToken();
      final response = await dio.get(
        '$baseUrl/api/foods',
        options: Options(headers: {if (token != null) 'Authorization': token}),
      );

      if (response.statusCode == 200) {
        final data = response.data;
        setState(() {
          foods = List<Map<String, dynamic>>.from(data['data'] ?? []);
          // 提取分类
          final categorySet = {'全部'};
          for (var food in foods) {
            categorySet.add(food['category'] ?? '其他');
          }
          categories = categorySet.toList();
          isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        error = '加载失败: $e';
        isLoading = false;
      });
      print('加载食品数据失败: $e');
    }
  }

  List<Map<String, dynamic>> get filteredFoods {
    if (selectedCategory == '全部') {
      return foods;
    }
    return foods.where((food) => food['category'] == selectedCategory).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '美食推荐',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        backgroundColor: Colors.orange.shade700,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: Column(
        children: [
          // 分类筛选
          _buildCategoryFilter(),

          // 食品列表
          Expanded(child: _buildFoodList()),
        ],
      ),
    );
  }

  Widget _buildCategoryFilter() {
    return Container(
      height: 50,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: categories.length,
        itemBuilder: (context, index) {
          final category = categories[index];
          final isSelected = category == selectedCategory;

          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: FilterChip(
              label: Text(category),
              selected: isSelected,
              onSelected: (selected) {
                setState(() {
                  selectedCategory = category;
                });
              },
              backgroundColor: Colors.grey.shade200,
              selectedColor: Colors.orange.shade100,
              checkmarkColor: Colors.orange.shade700,
            ),
          );
        },
      ),
    );
  }

  Widget _buildFoodList() {
    if (isLoading) {
      return const Center(
        child: CircularProgressIndicator(color: Colors.orange),
      );
    }

    if (error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            Text(error!, style: TextStyle(color: Colors.grey.shade600)),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: _loadFoodData, child: const Text('重试')),
          ],
        ),
      );
    }

    if (filteredFoods.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.restaurant_menu, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            Text('暂无美食推荐', style: TextStyle(color: Colors.grey.shade600)),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: filteredFoods.length,
      itemBuilder: (context, index) {
        return _buildFoodCard(filteredFoods[index]);
      },
    );
  }

  Widget _buildFoodCard(Map<String, dynamic> food) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      child: InkWell(
        onTap: () => _showFoodDetail(food),
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              // 食物图片
              Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.orange.shade50,
                ),
                child:
                    food['mainImage'] != null
                        ? ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: Image.network(
                            food['mainImage'].toString(),
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Icon(
                                Icons.restaurant,
                                color: Colors.orange.shade300,
                              );
                            },
                          ),
                        )
                        : Icon(
                          Icons.restaurant,
                          color: Colors.orange.shade300,
                          size: 32,
                        ),
              ),

              const SizedBox(width: 16),

              // 食物信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 名称和价格
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Text(
                            food['name'] ?? '未知美食',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Text(
                          '¥${food['price'] ?? 0}',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.orange.shade700,
                          ),
                        ),
                      ],
                    ),

                    const SizedBox(height: 4),

                    // 餐厅名称
                    if (food['restaurant'] != null &&
                        food['restaurant']['name'] != null)
                      Text(
                        food['restaurant']['name'].toString(),
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey.shade600,
                        ),
                      ),

                    const SizedBox(height: 8),

                    // 评分和分类
                    Row(
                      children: [
                        // 评分
                        Row(
                          children: [
                            Icon(Icons.star, color: Colors.amber, size: 16),
                            const SizedBox(width: 2),
                            Text(
                              '${food['rating'] ?? 0.0}',
                              style: const TextStyle(fontSize: 14),
                            ),
                          ],
                        ),

                        const SizedBox(width: 16),

                        // 分类标签
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.orange.shade100,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            food['category'] ?? '其他',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.orange.shade700,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showFoodDetail(Map<String, dynamic> food) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder:
          (context) => DraggableScrollableSheet(
            initialChildSize: 0.7,
            maxChildSize: 0.9,
            minChildSize: 0.5,
            builder:
                (context, scrollController) => Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(20),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 拖拽指示器
                      Container(
                        margin: const EdgeInsets.symmetric(vertical: 8),
                        width: 40,
                        height: 4,
                        decoration: BoxDecoration(
                          color: Colors.grey.shade300,
                          borderRadius: BorderRadius.circular(2),
                        ),
                      ),

                      Expanded(
                        child: SingleChildScrollView(
                          controller: scrollController,
                          padding: const EdgeInsets.all(20),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 标题
                              Text(
                                food['name'] ?? '美食详情',
                                style: const TextStyle(
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),

                              const SizedBox(height: 16),

                              // 基本信息
                              _buildDetailRow('价格', '¥${food['price'] ?? 0}'),
                              _buildDetailRow(
                                '评分',
                                '${food['rating'] ?? 0.0} ⭐',
                              ),
                              _buildDetailRow('分类', food['category'] ?? '其他'),
                              if (food['restaurant'] != null)
                                _buildDetailRow(
                                  '餐厅',
                                  food['restaurant']['name']?.toString() ??
                                      '未知餐厅',
                                ),
                              if (food['description']?.isNotEmpty == true) ...[
                                const SizedBox(height: 16),
                                const Text(
                                  '描述',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  food['description'],
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.grey.shade700,
                                    height: 1.5,
                                  ),
                                ),
                              ],
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
          ),
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          SizedBox(
            width: 60,
            child: Text(
              '$label:',
              style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
            ),
          ),
          Text(value, style: const TextStyle(fontSize: 14)),
        ],
      ),
    );
  }
}
